package com.bank.manage.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * SearcherRegion
 *
 * @author grl
 * @date 2024/4/1
 */
@Slf4j
public class SearcherRegion {

    private static Searcher searcher;

    public static String getRegion(String ip) {
        // jar包也能获取ip2region.xdb文件
        try {
            searcher = getSearcher();
            // 中国|0|上海|上海市|联通；美国|0|犹他|盐湖城|0
            String regionInfo = searcher.search(ip);
            String region = getCityInfo(regionInfo);
            return region;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解析城市信息，国内显示城市名，国外显示国家名
     */
    private static String getCityInfo(String regionInfo) {
        if (!StringUtils.isEmpty(regionInfo)) {
            String[] cityArr = regionInfo.replace("|0", "").replace("0|", "").split("\\|");
            if (cityArr.length > 0) {
                if ("内网ip".equalsIgnoreCase(cityArr[0])) {
                    return "内网IP";
                }
                if ("中国".equals(cityArr[0])) {
                    return cityArr[1];
                }
                return cityArr[0];
            }
        }
        return "未知IP";
    }

    private static   Searcher getSearcher() {
        if (searcher == null) {
            synchronized(SearcherRegion.class){
                if (searcher == null) {
                    InputStream inputStream = Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResourceAsStream("ip/ip2region.xdb");
                    byte[] bytes = InputStreamUtil.inputStreamToByteArray(inputStream);
                    try {
                        searcher = Searcher.newWithBuffer(bytes);
                    } catch (IOException e) {
                        log.error("获取 ip2region.xdb失败 ",e);
                    }
                }
            }
        }
        return searcher;
    }
}
